package com.lzq.springboot_lzq.controller;

import com.lzq.springboot_lzq.pojo.User;
import com.lzq.springboot_lzq.pojo.ResponseMessage;
import com.lzq.springboot_lzq.pojo.dto.UserDto;
import com.lzq.springboot_lzq.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController // 接口方法返回对象,转换成json文本
@RequestMapping("/user") // localhost:3939/user/**
public class UserController {

    @Autowired
    IUserService userService;

    //restful风格
    //增加
    @PostMapping ("/add")  // localhost:3939/user method=post
    public ResponseMessage<User> add(@Validated @RequestBody UserDto user){
        User userNew = userService.add(user);
        return ResponseMessage.success(userNew);
    }

    //删除
    @DeleteMapping ("/delete/{id}")
    public ResponseMessage<User> delete(@PathVariable int id) {
        User user = userService.findById(id);
        if (user != null) {
            userService.delete(id);
            return ResponseMessage.success(user);
        } else {
            return ResponseMessage.error(null);
        }
    }

    //修改
    @PutMapping("/edit")
    public ResponseMessage<User> edit(@Validated @RequestBody UserDto userNew) {
        User user = userService.findById(userNew.getId());
        if (user != null) {
            user = userService.edit(userNew);
            return ResponseMessage.success(user);
        } else {
            return ResponseMessage.error(null);
        }
    }

    //查询
    @GetMapping("/getById/{id}")
    public ResponseMessage<User> get(@PathVariable int id) {
        User user = userService.findById(id);
        if (user != null) {
            return ResponseMessage.success(user);
        } else {
            return ResponseMessage.error(null);
        }
    }
    // 查询所有用户并按ID从大到小排序
    @GetMapping("/getAll")
    public ResponseMessage<Iterable<User>> findAll() {
        Iterable<User> users = userService.findAll();
        return ResponseMessage.success(users);
    }
}
